#include "../include/header.h"
#define BUFFER_SIZE (1024 * 1024 * 8)
int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 3);
	int src_fd = open(argv[1], O_RDWR);
	ERROR_CHECK(src_fd, -1, "open src");


	// 获取源文件大小
	off_t src_size = lseek(src_fd, 0, SEEK_END);
	
	// 打开目标文件
	int dest_fd = open(argv[2],O_RDWR | O_CREAT | O_TRUNC, 0666);
	ERROR_CHECK(dest_fd, -1, "open dest");
	
	// 避免空间不足，提前占位
	int ret = ftruncate(dest_fd, src_size);
	ERROR_CHECK(ret, -1, "ftruncat");

	// 开始mmap
	off_t bytes_copied = 0; //记录已经复制的字节大小
	while(bytes_copied < src_size){
		// src未复制完

		off_t curr_cpy = (bytes_copied + BUFFER_SIZE) > src_size ? src_size - bytes_copied: BUFFER_SIZE;

		void *srcp = mmap(NULL, curr_cpy, PROT_READ, MAP_SHARED, src_fd, bytes_copied);
		ERROR_CHECK(srcp, MAP_FAILED, "mmap src");

		void *destp = mmap(NULL, curr_cpy, PROT_WRITE, MAP_SHARED, dest_fd, bytes_copied);
		ERROR_CHECK(destp, MAP_FAILED, "mmap destp");

		memcpy(destp, srcp, curr_cpy);
		munmap(srcp, curr_cpy);
		munmap(destp, curr_cpy);

		bytes_copied += curr_cpy;
	}

	

	close(src_fd);
	close(dest_fd);
	return 0;
}